import { ref, computed } from 'vue'

export default function useShortcut(props, groupRef) {
  var scrollRef = ref(null)
  const shortcutList = computed(() => {
    return props.data.map((group) => {
      return group.title
    })
  })
  // 对象的引用
  const touch = {}
  // 两个字母间的距离(一个小学线段的知识)
  const ANCHOR_HEIGHT = 18
  function onShortcutTouchStart(e) {
    const anchorIndex = parseInt(e.target.dataset.index)
    touch.y1 = e.touches[0].pageY
    touch.anchorIndex = anchorIndex
    scrollTo(anchorIndex)
  }

  function onShortcutTouchMove(e) {
    touch.y2 = e.touches[0].pageY
    // 为为整数偏移量(按照字母为线段点)
    const delta = ((touch.y2 - touch.y1) / ANCHOR_HEIGHT) | 0
    const anchorIndex = touch.anchorIndex + delta
    scrollTo(anchorIndex)
  }
  function scrollTo(index) {
    // 防止index的e.target 不是字母范围的容器
    if (isNaN(index)) {
      return false
    }
    // 让滑动的范围在字母之间
    index = Math.min(shortcutList.value.length - 1, index)
    index = Math.max(0, index)
    // 与上面min等同功能写法
    // if (index > shortcutList.value.length - 1 || index < 0) {
    //   return
    // }
    const targetEl = groupRef.value.children[index]
    const scroll = scrollRef.value.scroll
    scroll.scrollToElement(targetEl, 0)
  }
  return {
    shortcutList,
    onShortcutTouchStart,
    onShortcutTouchMove,
    scrollRef
  }
}
